<template>
	<a-modal v-bind="option" class="certificate-upload-dialog">
		<a-space :size="12">
			<file-upload v-model:file="front" :multiple="false">
				<template #icon>
					<svg-icon icon-class="certificate-front" />
				</template>
				<template #tip>证件正面</template>
			</file-upload>
			<file-upload v-model:file="back" :multiple="false">
				<template #icon>
					<svg-icon icon-class="certificate-back" />
				</template>
				<template #tip>证件反面</template>
			</file-upload>
		</a-space>
		<div v-color="{color: '#86909C'}">
			<small>请上传.jpg、png、jpeg格式图片</small>
		</div>
		<div class="error-color">
			<small>{{ errorTip }}</small>
		</div>
		<template #footer>
			<a-button type="primary" @click="save">确定</a-button>
		</template>
	</a-modal>
</template>

<script lang="ts" setup>
	import {Img} from 'yuxin-base/src/types'
	import {reactive, ref, toRef, watch, computed} from 'vue'
	import FileUpload from '@/components/common/file-upload.vue'

	const props = defineProps<{
		visible: boolean
		imgs: {
			// 证件正面
			frontImgUrl?: string | null
			// 证件反面
			rearImgUrl?: string | null
		}
	}>()

	const front = ref<Img>()
	const back = ref<Img>()

	const errorTip = computed(() => {
		const f = front.value?.url
		const b = back.value?.url
		return (f && b) || (!f && !b) ? '' : '证件正面和反面必须都上传或都不上传'
	})

	watch(
		() => props.visible,
		() => {
			front.value = {url: props.imgs.frontImgUrl}
			back.value = {url: props.imgs.rearImgUrl}
		}
	)

	const emits = defineEmits(['update:visible', 'confirm'])
	const option = reactive({
		title: '上传证件',
		width: 'auto',
		centered: true,
		keyboard: false,
		maskClosable: false,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		bodyStyle: {
			padding: '20px 16px'
		},
		onCancel() {
			emits('update:visible', false)
		}
	})

	const save = () => {
		const f = front.value?.url
		const b = back.value?.url
		if ((f && b) || (!f && !b)) {
			Object.assign(props.imgs, {
				// 证件正面
				frontImgUrl: front.value?.url,
				// 证件反面
				rearImgUrl: back.value?.url
			})
			emits('update:visible', false)
			emits('confirm', {front, back})
		}
	}
</script>
